package com.itheima.health.controller.backend;

import com.itheima.health.constant.MessageConstant;
import com.itheima.health.constant.RedisMessageConstant;
import com.itheima.health.entity.Result;
import com.itheima.health.utils.SMSUtils;
import com.itheima.health.utils.ValidateUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @package：com.itheima.health.controller.backend
 * @Author: mint
 * @Date: 2024/7/14 9:10
 */
@RestController("backendValidateCodeController")
@RequestMapping("/validatecode")
public class ValidateCodeController {
    @Resource
    private StringRedisTemplate stringredisTemplate;
    /**
     * 手机快速登录时发送手机验证码
     * @param telephone 手机号
     * @return
     */
    @GetMapping("/backendSend4Login.do")
    public Result send4Login(String telephone) {
        if (ValidateUtil.isValidatePhoneNumber(telephone)) {
            // 1.生成4位数字验证码
            String code = SMSUtils.sendValidateCode(telephone);
            // 3.判断短信是否发送成功? 是否为OK
            if (code != null) {
                // 3.1.短信发送成功，把验证码放到Redis中,存活时间5分钟
                stringredisTemplate.opsForValue().set(telephone + RedisMessageConstant.SENDTYPE_LOGIN, code, 15, TimeUnit.MINUTES);
                // 3.2.返回统一响应结果，Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
                return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
            }
            // 3.3.短信发送失败，返回统一响应结果，Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }
        return new Result(false, "手机号格式不正确");

    }
}
